package com.test.demo.activity;

import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.CalendarView;
import android.widget.FrameLayout;

import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.NET_DVR_PLAYBACK_INFO;
import com.hikvision.netsdk.NET_DVR_TIME;
import com.hikvision.netsdk.NET_DVR_VOD_PARA;
import com.hikvision.netsdk.PlaybackControlCommand;
import com.test.demo.R;
import com.test.demo.base.BaseActivity;
import com.test.demo.widget.RLPlaySurfaceView;

import butterknife.BindView;

/**
 * 回放
 */
public class PlayBackActivity extends BaseActivity implements SurfaceHolder.Callback {
    private static final String IP = "192.168.1.104";
    private static final int PORT = 8000;
    private static final String UNAME = "admin";
    private static final String UPWD = "gyzn2018";
    @BindView(R.id.sv_palyer_content)
    SurfaceView m_osurfaceView = null;

    @BindView(R.id.cv_datetime)
    CalendarView cvDatetime;

    private int m_iPlayID = -1; // return by NET_DVR_RealPlay_V40
    private int m_iPlaybackID = -1; // return by NET_DVR_PlayBackByTime
    private static final String TAG = "PlaybackActivity";
    private RLPlaySurfaceView rlPlaySurfaceView;
    private boolean m_bPlaybackByName = false;
    private int m_iStartChan;
    private int m_iLogID;

    @Override
    public int getContentView() {
        return R.layout.activity_play_back;
    }

    @Override
    protected void init() {
        m_iLogID = getIntent().getIntExtra("m_iLogID", m_iLogID);
        m_iStartChan = getIntent().getIntExtra("m_iStartChan", m_iStartChan);
        Log.e(TAG, "init: m_iLogID=" + m_iLogID);
        Log.e(TAG, "init: m_iStartChan=" + m_iStartChan);
        cvDatetime.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView calendarView, int year, int month, int dayOfMonth) {

            }
        });
        m_osurfaceView.getHolder().addCallback(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ChangeSingleSurFace();
            }
        },2000);
    }

    private void ChangeSingleSurFace() {
        rlPlaySurfaceView = new RLPlaySurfaceView(this);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        rlPlaySurfaceView.getPlaySurfaceView().setParam(metric.widthPixels);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = rlPlaySurfaceView.getPlaySurfaceView().getM_iHeight();
        params.leftMargin = rlPlaySurfaceView.getPlaySurfaceView().getM_iWidth();
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        addContentView(rlPlaySurfaceView, params);
        rlPlaySurfaceView.setVisibility(View.VISIBLE);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startPlay();
            }
        },2000);

    }

    private void startPlay() {
        try {
            if (m_iLogID < 0) {
                Log.e(TAG, "please login on a device first");
                return;
            }
            if (m_iPlaybackID < 0) {
                if (m_iPlayID >= 0) {
                    Log.e(TAG, "Please stop preview first");
                    return;
                }


                if (!m_bPlaybackByName) {
                    NET_DVR_TIME timeStart = new NET_DVR_TIME();
                    NET_DVR_TIME timeStop = new NET_DVR_TIME();

                    timeStart.dwYear = 2019;
                    timeStart.dwMonth = 8;
                    timeStart.dwDay = 4;
                    timeStart.dwHour = 18;
                    timeStart.dwMinute = 0;
                    timeStart.dwSecond = 0;

                    timeStop.dwYear = 2019;
                    timeStop.dwMonth = 8;
                    timeStop.dwDay = 4;
                    timeStop.dwHour = 22;
                    timeStop.dwMinute = 0;
                    timeStop.dwSecond = 0;

                    NET_DVR_VOD_PARA vodParma = new NET_DVR_VOD_PARA();
                    vodParma.struBeginTime = timeStart;
                    vodParma.struEndTime = timeStop;
                    vodParma.byStreamType = 1;
                    vodParma.struIDInfo.dwChannel = m_iStartChan;
                    vodParma.hWnd = rlPlaySurfaceView.getPlaySurfaceView().getHolder().getSurface();
                    Log.e(TAG, "onClick: " + vodParma);
                    m_iPlaybackID = HCNetSDK.getInstance().NET_DVR_PlayBackByTime_V40(m_iLogID, vodParma);
                    Log.e(TAG, "onClick: " + m_iPlaybackID);
                           /*reverse playback
                            NET_DVR_PLAYCOND playcond = new NET_DVR_PLAYCOND();
                   	 	playcond.dwChannel = m_iStartChan;
                   	 	playcond.struStartTime = timeStart;
                   	 	playcond.struStopTime = timeStop;
                   	 	playcond.byDrawFrame = 0;
                   	 	playcond.byStreamType = 1;

                        m_iPlaybackID = HCNetSDK.getInstance().NET_DVR_PlayBackReverseByTime_V40(m_iLogID, players[0].getHolder().getSurface(), playcond);
                        */
                } else {
                    m_iPlaybackID = HCNetSDK.getInstance().NET_DVR_PlayBackByName(m_iLogID, new String("ch0001_00000000300000000"), rlPlaySurfaceView.getPlaySurfaceView().getHolder().getSurface());
                }

                if (m_iPlaybackID >= 0) {
                    NET_DVR_PLAYBACK_INFO struPlaybackInfo = null;
                    if (!HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYSTART, null, 0, null)) {
                        Log.e(TAG, "net sdk playback start failed!");
                        return;
                    }

                       /*Test code
                          if(HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYPAUSE, null, 0, struPlaybackInfo))
                   	   {
                   		   Log.i(TAG, "NET_DVR_PlayBackControl_V40 pause succ");
                   	   }
                   	   if(HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYRESTART, null, 0, struPlaybackInfo))
                   	   {
                   		   Log.i(TAG, "NET_DVR_PLAYRESTART restart succ");
                   	   }
                   	   if(HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYFAST, null, 0, struPlaybackInfo))
                   	   {
                   		   Log.i(TAG, "NET_DVR_PLAYFAST succ");
                   	   }
                   	   if(HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYSLOW, null, 0, struPlaybackInfo))
                   	   {
                   		   Log.i(TAG, "NET_DVR_PLAYSLOW succ");
                   	   }
                   	   if(HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYSTARTAUDIO, null, 0, struPlaybackInfo))
                   	   {
                   		   Log.i(TAG, "NET_DVR_PLAYSTARTAUDIO succ");
                   	   }
                   	   byte[] lpInBuf = new byte[60];
                   	   lpInBuf[0] = 5;
                   	   if(HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYAUDIOVOLUME, lpInBuf, 4, struPlaybackInfo))
                   	   {
                   		   Log.i(TAG, "NET_DVR_PLAYAUDIOVOLUME succ");
                   	   }
                   	   else
                   	   {
                     	 Log.e(TAG, "NET_DVR_PLAYAUDIOVOLUME fail");
                   	   }
                   	   if(HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYSTOPAUDIO, null, 0, struPlaybackInfo))
                   	   {
                   		   Log.i(TAG, "NET_DVR_PLAYSTOPAUDIO succ");
                   	   }
					   */


                    Thread thread11 = new Thread() {
                        public void run() {
                            int nProgress = -1;
                            while (true) {
                                nProgress = HCNetSDK.getInstance().NET_DVR_GetPlayBackPos(m_iPlaybackID);
                                System.out.println("NET_DVR_GetPlayBackPos:" + nProgress);
                                if (nProgress < 0 || nProgress >= 100) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) { // TODO
                                    e.printStackTrace();
                                }
                            }
                        }
                    };
                    thread11.start();

                } else {
                    Log.i(TAG, "NET_DVR_PlayBackByName failed, error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                }
            } else {
                if (!HCNetSDK.getInstance().NET_DVR_StopPlayBack(m_iPlaybackID)) {
                    Log.e(TAG, "net sdk stop playback failed");
                } // player stop play
                m_iPlaybackID = -1;
            }
        } catch (Exception err) {
            Log.e(TAG, "error: " + err.toString());
        }
    }

    public void onBack(View view) {
        finish();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        m_osurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        Log.i(TAG, "surface is created");

        //valid just when single channel preview
        if (-1 == m_iPlayID && -1 == m_iPlaybackID) {
            return;
        }
        rlPlaySurfaceView.getPlaySurfaceView().m_hHolder = holder;
        Surface surface = holder.getSurface();
        if (surface.isValid()) {
            if (m_iPlayID != -1) {
                if (-1 == HCNetSDK.getInstance().NET_DVR_RealPlaySurfaceChanged(m_iPlayID, 0, holder)) {
                    Log.e(TAG, "Player setVideoWindow failed!");
                }
            } else {
                if (-1 == HCNetSDK.getInstance().NET_DVR_PlayBackSurfaceChanged(m_iPlaybackID, 0, holder)) {
                    Log.e(TAG, "Player setVideoWindow failed!");
                }
            }

        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("m_iPlayID", m_iPlayID);
        super.onSaveInstanceState(outState);
        Log.i(TAG, "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        m_iPlayID = savedInstanceState.getInt("m_iPlayID");
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG, "onRestoreInstanceState");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(TAG, "Player setVideoWindow release!");
        if (-1 == m_iPlayID && -1 == m_iPlaybackID) {
            return;
        }
        if (holder.getSurface().isValid()) {
            if (m_iPlayID != -1) {
                if (-1 == HCNetSDK.getInstance().NET_DVR_RealPlaySurfaceChanged(m_iPlayID, 0, null)) {
                    Log.e(TAG, "Player setVideoWindow failed!");
                }
            } else {
                if (-1 == HCNetSDK.getInstance().NET_DVR_PlayBackSurfaceChanged(m_iPlaybackID, 0, null)) {
                    Log.e(TAG, "Player setVideoWindow failed!");
                }
            }
        }
    }
}
